<?php

namespace App\Http\Controllers\organization;

use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\organization\Grade;
use Mockery\Exception;

class GradeController extends Controller
{
    //新增年级
    public function createGrade(Request $request)
    {
        $result = $this->result();
        //获取参数
        $request = $this->getRequest($request);
        try
        {
            $Validator = Validator::make($request, [
                //必填，唯一,20字符以内
                'grade'     =>  'required | max:20 | unique:grades',
            ]);

            //验证失败
            if($Validator->fails())
            {
                $errors = $Validator->errors();
                throw new Exception($errors->first('grade'), config('result.errorValidatorCode'));
            }

            $params['grade'] = trim($request['grade']);

            $grade = new Grade();
            $grade->create($params);
        }
        catch (Exception $exception)
        {
            $result['errorCode'] = $exception->getCode();
            $result['errorMsg']  = $exception->getMessage();
        }

        return $result;
    }

    /**
     * 获取年级列表
     * @return mixed
     * errorCode,errorMsg,data,total,current_page,last_page,next_page_url,prev_page_url
     */
    public function getGradeList()
    {
        $result = $this->result();
        $data = array();
        try
        {
            $grades = new Grade();
            $data = $grades->select(['id', 'grade'])->paginate(config('app.pageSize'))->toArray();
            if(empty($data['data']))
            {
                throw new Exception(config('result.errorGetGradeMsg'), config('result.errorGetGradeCode'));
            }
            //获取的数据
            $result['data']          = $data['data'];
            //总条数
            $result['total']         = $data['total'];
            //当前页码
            $result['current_page']  = $data['current_page'];
            //最后一页页码
            $result['last_page']     = $data['last_page'];
            //下一页url
            $result['next_page_url'] = $data['next_page_url'];
            //上一页url
            $result['prev_page_url'] = $data['prev_page_url'];
        }
        catch (Exception $exception)
        {
            $result['errorCode'] = $exception->getCode();
            $result['errorMsg']  = $exception->getMessage();
        }

        return $result;
    }



}
